<template>
  <div>
    <SelectConfigData id="data" ref="selectConfigDataRefs" v-model="dataForm"/>
    <ChartStyle id="style" ref="chartStyleRef" v-model="dataForm"/>
    <Preview ref="previewRef" />
    <fixed-pagination>
      <div class="center">
        <PlainCreateBtn :show-icon="false" style="width: 80px;" size="small" @click="preview">预览</PlainCreateBtn>
        <el-button :loading="btnLoading" type="primary" size="small" @click="toSubmit">保存</el-button>
        <el-button class="cancel-btn-style" type="info" size="small" @click="handleClose">取消</el-button>
      </div>
      <div v-if="isEdit" class="foot-info">
        <div class="item">更新人：{{ dataForm.updateUserName || '--' }}</div>
        <div class="item">
          更新时间：
          <span v-if="dataForm.updateTime">{{ dataForm.updateTime | format('YYYY/MM/DD HH:mm') }}</span>
          <span v-else>--</span>
        </div>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import ChartStyle from './chartStyle';
import Preview from './preview';
import SelectConfigData from './selectConfigData';
import { parseJson } from '@/utils';
import { createChartTable, editChartTable } from '@/api/reportManage';
import HandelParams from '../../mixins/handelParams';
import ElMessage from '@/utils/message';
import { format } from '@/filters/date';

export default {
  components: { ChartStyle, SelectConfigData, Preview },
  filters: { format },
  mixins: [HandelParams],
  props: {
    process: {
      type: Number,
      default: 0
    },
    tabId: {
      type: String | Number,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      btnLoading: false,
      dataForm: {
        kind: 3,
        name: '',
        layout: '',
        layoutNum: 36,
        type: 1,

        chartFilter: [{
          filterName: '筛选组1',
          report: [],
          system: []
        }],
        dataSheet: '', // 数据表id
        linkDataSheet: [], // 关联字段数据表列表
        linkFieldName: '', // 关联字段
        selectField: [],
        combFields: [], // 公式字段
        yAxis: null,
        yAxisCombo: '',
        xAxis: '',
        showXAxis: true,
        showYAxis: true,
        isOrder: false,
        sortField: '',
        sortFieldName: '',
        sortType: '',
        sortShowType: 1, // 0:正 1:负
        isDataLabel: true,
        isGrid: false,
        isLegend: true,
        isChartTitle: true,
        isUpdateRegularly: false,
        updateRegularlyType: '1小时',
        isSaveToReport: false,
        showNums: undefined,
        chartColor: '0',
        styleConfig: '',
        dataShowType: '',
        contrastTime: '',
        contrastTimeRange: [],
        isSplitChunk: false,
        chunkSeparator: '',
        isShow: true,
        hasDataSource: false
      },
      defaultLayout: { x: 0, y: 0, h: 0 },
      defaultData: null
    };
  },
  mounted() {
    if (this.$refs.chartStyleRef) {
      this.$refs.chartStyleRef.getData();
    }
    this.defaultData = JSON.parse(JSON.stringify(this.dataForm));
  },
  methods: {
    // 编辑时注入数据
    setDefault(data) {
      this.setDefaultTime(data);
      this.dataForm = data;
      const layout = parseJson(data.layout);
      // Object.assign(dataForm, data);
      const dataForm = this.dataForm;
      this.defaultLayout = layout;
      dataForm.layoutNum = Number(layout.w || 12);

      if (this.$refs.chartStyleRef && dataForm.id) {
        this.$refs.chartStyleRef.setStyleDefault(dataForm.styleConfig);
      }
      if (this.dataForm.type === 13) {
        if (typeof this.dataForm.yAxis !== 'string') this.dataForm.yAxis = this.dataForm.yAxis.join('');
      }
      this.$nextTick(() => {
        if (this.$refs.selectConfigDataRefs) {
          this.$refs.selectConfigDataRefs.setDefault(dataForm);
        }
      });

      if (data.contrastTime) {
        setTimeout(() => {
          this.$nextTick(i => {
            this.$set(this.dataForm, 'contrastTime', data.contrastTime || '');
          });
        }, 200);
      }
    },
    isDataChange() {
      if (this.$refs.chartStyleRef) {
        this.$refs.chartStyleRef.getData();
      }
      return JSON.stringify(this.dataForm) !== JSON.stringify(this.defaultData);
    },
    toSubmit() {
      const chartStyleRef = this.$refs.chartStyleRef;
      this.$refs.selectConfigDataRefs.submitField();
      const dataForm = chartStyleRef.getData();
      const validatePromise = [];
      validatePromise.push(this.$refs.selectConfigDataRefs.validate());
      this.handelChartFilter(dataForm);
      if (dataForm.isSplitChunk && !dataForm.chunkSeparator) {
        ElMessage.error('请输入拆分标识');
        return;
      }
      Promise.all(validatePromise).then(() => {
        if (!dataForm.dataSheet) {
          this.$message.error('请选择数据表');
          return;
        }
        if (!dataForm.xAxis || !dataForm.yAxis || dataForm.yAxis.length === 0) {
          this.$message.error('请选择统计字段');
          return;
        }
        if (dataForm.yAxis.length > 10) {
          this.$message({ type: 'warning', message: '图例项最多选择10个' });
          return;
        }
        const layout = this.defaultLayout;
        layout.w = dataForm.layoutNum;
        dataForm.layout = JSON.stringify(layout);
        dataForm.tabId = this.tabId;
        dataForm.isMobile = this.$route.query.editMobileMode ? 1 : 0;
        if (!this.isEdit || this.editType === 'copy') {
          this.add(dataForm);
        } else {
          this.edit(dataForm);
        }
      }).catch(err => {
        console.log(err);
        this.$message.error('请检查信息是否填写完整');
      });
    },
    add(dataForm) {
      this.btnLoading = true;
      createChartTable(dataForm).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('新增成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
        // this.$message.error(err.message);
      });
    },
    edit(dataForm) {
      this.btnLoading = true;
      dataForm.id = this.$route.params.id || '';
      editChartTable(dataForm).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
        // this.$message.error(err.message);
      });
    },
    preview() {
      const chartStyleRef = this.$refs.chartStyleRef;
      this.$refs.selectConfigDataRefs.submitField();
      const dataForm = chartStyleRef.getData();
      this.handelChartFilter(dataForm);
      this.$refs.previewRef.open(dataForm);
    },
    handleClose() {
      this.$emit('goBack');
    },
    switchProcess({ id }) {
      this.$emit('switchProcess', { id });
    }
  }
};
</script>

<style lang="scss" scoped>
.foot-info {
  display: flex;
  align-items: center;
  position: absolute;
  right: 10px;
  .item {
    flex-shrink: 0;
    margin-left: 10px;
    color: #999;
  }
}
</style>
